
package com.crowdfunding.circle.user.controller;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.crowdfunding.circle.common.controller.BaseController;
import com.crowdfunding.circle.common.param.SessionUserInfo;
import com.crowdfunding.circle.config.ConfigUtils;
import com.crowdfunding.circle.constant.PageIdEnum;
import com.crowdfunding.circle.permission.service.PermissionService;
import com.crowdfunding.circle.permission.service.RoleService;
import com.crowdfunding.circle.question.service.QuestionService;
import com.crowdfunding.circle.sensitiveword.SensitiveWordUtils;
import com.crowdfunding.circle.trade.service.TradeRecordService;
import com.crowdfunding.circle.user.entity.UserInfoVO;
import com.crowdfunding.circle.user.param.UserInfoParam;
import com.crowdfunding.circle.user.service.UserInfoService;

/**
 * 用户信息Controller
 *
 * @author 朱国军
 * @since 1.0
 * @version 2015年12月27日 朱国军
 */
@Controller
public class UserInfoController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(UserInfoController.class);

    @Autowired
    private UserInfoService userInfoService;
    
    @Autowired
    private RoleService roleService;
    
    @Autowired
    private PermissionService permissionService;

    @Autowired
    private QuestionService questionService;

    @Autowired
    private TradeRecordService tradeRecordService;

    private final static String ADMIN_LIST_PAGE = "/admin/account_manage";

    private final static String VIEW_PAGE = "/account/user_view";

    private final static String UPDATE_PAGE = "/account/user_edit";

    private final static String LOGIN_PAGE = "/login/login";
    
    private final static String REGISTER_PAGE = "/login/register";
    
    private static final String RESET_PASSWORD_PAGE = "/account/reset_password";

    @RequestMapping(value = "/uncheck/login")
    public ModelAndView login(String redirectUrl) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("redirectUrl", redirectUrl);
        return new ModelAndView(LOGIN_PAGE, resultMap);
    }

    @RequestMapping(value = "/uncheck/register")
    public ModelAndView register(String redirectUrl) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("redirectUrl", redirectUrl);
        return new ModelAndView(REGISTER_PAGE, resultMap);
    }
    
    @RequestMapping(value = "/uncheck/doLogin", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String doLogin(String userAccount, String userPassword, String imageCode) {
        JSONObject result = new JSONObject();

        if (StringUtils.isBlank(userPassword) || StringUtils.isBlank(userAccount)) {
            result.put("result", false);
            result.put("msg", "用户名或密码不能为空");
            return result.toString();
        }

        List<UserInfoVO> userList = userInfoService.queryUserByName(null, userAccount);
        UserInfoVO userInfo = new UserInfoVO();
        if (userList == null || userList.size() != 1) {
            result.put("result", false);
            result.put("msg", "用户不存在");
            return result.toString();
        } else {
            userInfo = userList.get(0);
        }

        if (StringUtils.equals(userPassword, userInfo.getUserPassword())) {
            SessionUserInfo sessionUserInfo = new SessionUserInfo();
            String userId = userInfo.getUserId();
            sessionUserInfo.setUserId(userId);
            sessionUserInfo.setUserName(userInfo.getUserName());

            sessionUserInfo.setUserInfo(userInfo);

            sessionUserInfo.setPermissionList(permissionService.queryPermissionByUserId(userId));
            sessionUserInfo.setRoleList(roleService.queryRoleByUserId(userId));

            session.setAttribute("sessionUserInfo", sessionUserInfo);
            
            Integer questionCount = questionService.queryQuerstionCount(userId);

            session.setAttribute("questionCount", questionCount);

            BigDecimal totalFee = tradeRecordService.queryTotalFee(userId);
            
            if (totalFee == null) {
                totalFee = new BigDecimal(0);
            }
            
            session.setAttribute("totalFee", totalFee);

            result.put("result", true);
            result.put("msg", "成功");
            return result.toString();
        } else {
            result.put("result", false);
            result.put("msg", "用户名或密码错误");
            return result.toString();
        }
    }
    
    @RequestMapping(value = "/check/logout")
    public ModelAndView logout() {
        session.removeAttribute("sessionUserInfo");
        return new ModelAndView("redirect:/");
    }

    @RequestMapping(value = "/uncheck/doRegister", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String doRegister(String userName, String userAccount, String userPassword, String confirmPassword, String imageCode, String email) {
        JSONObject result = new JSONObject();
        if (StringUtils.isBlank(userName)) {
            result.put("result", false);
            result.put("msg", "昵称不能为空");
            return result.toString();
        }
        
        if (StringUtils.isBlank(userAccount)) {
            result.put("result", false);
            result.put("msg", "帐号不能为空");
            return result.toString();
        }
        
        if (StringUtils.isBlank(userPassword) || StringUtils.isBlank(confirmPassword)) {
            result.put("result", false);
            result.put("msg", "用户密码不能为空");
            return result.toString();
        }
        
        if (StringUtils.isBlank(imageCode)) {
            result.put("result", false);
            result.put("msg", "图片验证码不能为空");
            return result.toString();
        }
        
        String sessionImageCode = String.valueOf(session.getAttribute(PageIdEnum.REGISTER.getId() + "_imageCode"));
        
        if (!StringUtils.equals(imageCode, sessionImageCode) || StringUtils.isBlank(sessionImageCode)) {
            result.put("result", false);
            result.put("msg", "图片验证码不正确");
            return result.toString();
        }
        
        if (!StringUtils.equals(userPassword, confirmPassword)) {
            result.put("result", false);
            result.put("msg", "两次输入的密码不一致");
            return result.toString();
        }
        
        List<UserInfoVO> oldUserList = userInfoService.queryUserByName(userName, userAccount);
        
        if (oldUserList != null && oldUserList.size() > 0) {
            for (UserInfoVO oldUser : oldUserList) {
                if (StringUtils.equals(userName, oldUser.getUserName())) {
                    result.put("result", false);
                    result.put("msg", "该昵称已存在");
                    return result.toString();
                } else if (StringUtils.equals(userAccount, oldUser.getUserAccount())) {
                    result.put("result", false);
                    result.put("msg", "该帐号已存在");
                    return result.toString();
                }
            }
        }
        String userAccountPattern = "^[a-zA-Z0-9_][a-zA-Z0-9_]{5,14}$";

        if (!Pattern.matches(userAccountPattern, userAccount)) {
            result.put("result", false);
            result.put("msg", "帐号不符合规范，帐号允许输入字母、_、数字，长度6到15位");
            return result.toString();
        }
        String userPasswordPattern = "^[a-zA-Z0-9_]{6,15}$";
        if (!Pattern.matches(userPasswordPattern, userPassword)) {
            result.put("result", false);
            result.put("msg", "密码不符合规范，密码长度6到15位，允许输入字母、数字、_");
            return result.toString();
        }

        String userNamePattern = "^[a-zA-Z0-9\u4e00-\u9fa5]{2,10}$";

        if (!Pattern.matches(userNamePattern, userName)) {
            result.put("result", false);
            result.put("msg", "昵称不符合规范，昵称长度2到10位，允许输入字母、数字、汉字");
            return result.toString();
        }

        if (SensitiveWordUtils.isContaintSensitiveWord(userName, 1)) {
            result.put("result", false);
            result.put("message", "昵称中包含敏感词汇" + SensitiveWordUtils.getSensitiveWord(userName, 1) + "，请检查后再保存");
            return JSONObject.toJSONString(result);
        }
        
        if (SensitiveWordUtils.isContaintSensitiveWord(userAccount, 1)) {
            result.put("result", false);
            result.put("message", "帐号信息中包含敏感词汇" + SensitiveWordUtils.getSensitiveWord(userAccount, 1) + "，请检查后再保存");
            return JSONObject.toJSONString(result);
        }

        if (SensitiveWordUtils.isContaintSensitiveWord(email, 1)) {
            result.put("result", false);
            result.put("message", "邮箱中包含敏感词汇" + SensitiveWordUtils.getSensitiveWord(email, 1) + "，请检查后再保存");
            return JSONObject.toJSONString(result);
        }
        
        UserInfoVO userInfoVO = new UserInfoVO();
        String userId = UUID.randomUUID().toString();
        userInfoVO.setUserId(userId);
        userInfoVO.setUserAccount(userAccount);
        userInfoVO.setUserName(userName);
        userInfoVO.setUserPassword(userPassword);
        userInfoVO.setEmail(email);
        userInfoVO.setDataStatus(0);

        userInfoVO.setHeadImage(ConfigUtils.getStringValueByKey("user.default_image"));
        
        Integer insertCount = userInfoService.insert(userInfoVO);
        if (insertCount == 1) {
            SessionUserInfo sessionUserInfo = new SessionUserInfo();

            sessionUserInfo.setUserId(userId);
            sessionUserInfo.setUserName(userInfoVO.getUserName());

            sessionUserInfo.setUserInfo(userInfoVO);

            sessionUserInfo.setPermissionList(permissionService.queryPermissionByUserId(userId));
            sessionUserInfo.setRoleList(roleService.queryRoleByUserId(userId));

            session.setAttribute("sessionUserInfo", sessionUserInfo);

            Integer questionCount = questionService.queryQuerstionCount(userId);

            session.setAttribute("questionCount", questionCount);
            
            result.put("result", true);
            result.put("msg", "成功");
            return result.toString();
        } else {
            result.put("result", false);
            result.put("msg", "系统异常，新增用户数据出错");
            return result.toString();
        }
    }
    
    @RequestMapping(value = "/account/user/toUpdate")
    public ModelAndView intoUpdate() {
        SessionUserInfo seUser = (SessionUserInfo) session.getAttribute("sessionUserInfo");
        Map<String, Object> resultMap = new HashMap<String, Object>();
        UserInfoVO userInfoVO = userInfoService.findById(seUser.getUserId());
        resultMap.put("user", userInfoVO);
        return new ModelAndView(UPDATE_PAGE, resultMap);
    }
    
    @RequestMapping(value = "/account/user/update", produces = "application/json;charset=utf-8;")
    @ResponseBody
    public String update(UserInfoVO userInfoVO) {
        SessionUserInfo seUser = (SessionUserInfo) session.getAttribute("sessionUserInfo");
        userInfoVO.setUserId(seUser.getUserId());
        
        JSONObject result = new JSONObject();
        String userName = userInfoVO.getUserName();
        if (StringUtils.isBlank(userName)) {
            result.put("result", false);
            result.put("msg", "昵称不能为空");
            return result.toJSONString();
        }
        
        String userNamePattern = "^[a-zA-Z0-9\u4e00-\u9fa5]{2,10}$";

        if (!Pattern.matches(userNamePattern, userName)) {
            result.put("result", false);
            result.put("msg", "昵称不符合规范，昵称长度2到10位，允许输入字母、数字、汉字");
            return result.toJSONString();
        }

        List<UserInfoVO> oldUserList = userInfoService.queryUserByName(userName, null);
        
        if (oldUserList != null && oldUserList.size() > 0) {
            for (UserInfoVO oldUser : oldUserList) {
                if (StringUtils.equals(userName, oldUser.getName()) && !StringUtils.equals(oldUser.getUserId(), seUser.getUserId())) {
                    result.put("result", false);
                    result.put("msg", "该昵称已存在");
                    return result.toJSONString();
                }
            }
        }
        
        if (SensitiveWordUtils.isContaintSensitiveWord(userInfoVO.getUserName(), 1)) {
            result.put("result", false);
            result.put("message", "昵称中包含敏感词汇" + SensitiveWordUtils.getSensitiveWord(userInfoVO.getUserName(), 1) + "，请检查后再保存");
            return JSONObject.toJSONString(result);
        }

        try {
            Integer updateCount = userInfoService.update(userInfoVO);
            if (updateCount != null && updateCount == 1) {

                SessionUserInfo sessionUserInfo = new SessionUserInfo();
                String userId = userInfoVO.getUserId();
                sessionUserInfo.setUserId(userId);
                sessionUserInfo.setUserName(userInfoVO.getUserName());

                sessionUserInfo.setUserInfo(userInfoVO);

                sessionUserInfo.setPermissionList(permissionService.queryPermissionByUserId(userId));
                sessionUserInfo.setRoleList(roleService.queryRoleByUserId(userId));

                session.setAttribute("sessionUserInfo", sessionUserInfo);

                result.put("result", true);
                result.put("message", "修改用户信息成功");

            } else {
                result.put("result", false);
                result.put("message", "修改用户信息失败");
            }
        } catch (Exception e) {
            logger.error("修改用户信息出错", e);
            result.put("result", false);
            result.put("message", "修改用户信息出错：" + e.getLocalizedMessage());
        }
        return result.toJSONString();
    }
    
    @RequestMapping(value = "/account/user/resetPassword", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String resetPassword(String oldPassword, String password, String confirmPassword, String imageCode) {
        SessionUserInfo seUser = (SessionUserInfo) session.getAttribute("sessionUserInfo");

        JSONObject result = new JSONObject();

        if (StringUtils.isBlank(password) || StringUtils.isBlank(confirmPassword)) {
            result.put("result", false);
            result.put("msg", "用户密码不能为空");
            return result.toString();
        }

        if (StringUtils.isBlank(imageCode)) {
            result.put("result", false);
            result.put("msg", "图片验证码不能为空");
            return result.toString();
        }

        String sessionImageCode = String.valueOf(session.getAttribute(PageIdEnum.RESET_PASSWORD.getId() + "_imageCode"));

        if (!StringUtils.equals(imageCode, sessionImageCode) || StringUtils.isBlank(sessionImageCode)) {
            result.put("result", false);
            result.put("msg", "图片验证码不正确");
            return result.toString();
        }

        if (!StringUtils.equals(password, confirmPassword)) {
            result.put("result", false);
            result.put("msg", "两次输入的密码不一致");
            return result.toString();
        }

        String userPasswordPattern = "^[a-zA-Z0-9_]{6,15}$";
        if (!Pattern.matches(userPasswordPattern, password)) {
            result.put("result", false);
            result.put("msg", "密码不符合规范，密码长度6到15位，允许输入字幕、数字、_");
            return result.toString();
        }

        UserInfoVO userInfo = userInfoService.findById(seUser.getUserId());
        if (!StringUtils.equals(oldPassword, userInfo.getUserPassword())) {
            logger.error("修改用户密码时，旧密码输入错误");
            result.put("result", false);
            result.put("message", "旧密码输入错误");
            return result.toString();
        }

        UserInfoVO userInfoVO = new UserInfoVO();
        userInfoVO.setUserId(seUser.getUserId());
        userInfoVO.setUserPassword(password);
        try {
            Integer updateCount = userInfoService.update(userInfoVO);
            if (updateCount != null && updateCount == 1) {
                result.put("result", true);
                result.put("message", "修改用户密码成功");
            } else {
                result.put("result", false);
                result.put("message", "修改用户密码失败");
            }
        } catch (Exception e) {
            logger.error("修改用户密码出错", e);
            result.put("result", false);
            result.put("message", "修改用户密码出错：" + e.getLocalizedMessage());
        }
        return result.toJSONString();
    }
    
    @RequestMapping(value = "/admin/user/delete/{id}", produces = "application/json;charset=utf-8;")
    @ResponseBody
    public String delete(@PathVariable String id) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        try {
            Integer deleteCount = userInfoService.delete(id);
            if (deleteCount != null && deleteCount == 1) {
                resultMap.put("result", true);
                resultMap.put("message", "删除用户信息成功");
            } else {
                resultMap.put("result", false);
                resultMap.put("message", "删除用户信息失败");
            }
        } catch (Exception e) {
            logger.error("删除用户信息出错", e);
            resultMap.put("result", false);
            resultMap.put("message", "删除用户信息出错：" + e.getLocalizedMessage());
        }
        return JSONObject.toJSONString(resultMap);
    }

    @RequestMapping(value = "/admin/user/list", produces = "text/html;charset=utf-8;")
    @ResponseBody
    public ModelAndView queryList(UserInfoParam userInfoParam) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        List<UserInfoVO> dataList = userInfoService.queryByPage(userInfoParam);
        resultMap.put("dataList", dataList);
        resultMap.put("paramMap", userInfoParam);
        return new ModelAndView(ADMIN_LIST_PAGE, resultMap);
    }
    
    @RequestMapping(value = "/account/user/view", produces = "text/html;charset=utf-8;")
    @ResponseBody
    public ModelAndView viewConfigInfo() {
        SessionUserInfo seUser = (SessionUserInfo) session.getAttribute("sessionUserInfo");
        Map<String, Object> resultMap = new HashMap<String, Object>();
        UserInfoVO userInfoVO = userInfoService.findById(seUser.getUserId());
        resultMap.put("user", userInfoVO);
        return new ModelAndView(VIEW_PAGE, resultMap);
    }
    
    @RequestMapping(value = "/account/user/toResetPassword", produces = "text/html;charset=utf-8;")
    @ResponseBody
    public ModelAndView toResetPassword() {
        return new ModelAndView(RESET_PASSWORD_PAGE);
    }
}
